package com.kafka.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;


/**
 * 分区生产者
 *
 */
public class PartitionProducer {

    public static void main(String[] args) {

        Properties props = new Properties();


        // Kafka 服务端的主机名和端口号
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.100.125:9092");


        // 自定义分区
//        props.put("partitioner.class", "com.kafka.paratition.MyParatition");


        // key 序列化
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        // value 序列化
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer(props);

        for (int i = 0; i < 50; i++) {

            // 指定相同的key 会发送到相同的分区partition
            producer.send(new ProducerRecord<String, String>("first", "KKB",

                    "hello world-" + i), new Callback() {

                public void onCompletion(RecordMetadata metadata, Exception exception) {

                    if (exception == null) {

                        System.out.println(metadata.partition()+ "-----"+ metadata.offset());

                    } else {

                        exception.printStackTrace();
                    }
                }

            });
        }

        producer.close();
    }
}
